package com.qst.crop.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.qst.crop.dao.KnowledgeDao;
import com.qst.crop.entity.Knowledge;
import com.qst.crop.service.KnowledgeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class KnowledgeServiceImpl implements KnowledgeService {

    @Autowired

    private KnowledgeDao knowledgeDao;

    private Integer pageSize=30;
    @Override
    public PageInfo<Knowledge> findAll(Integer pageNum) {
        PageHelper.startPage(pageNum,pageSize);
        List<Knowledge> knowledgeList=knowledgeDao.selectAll();
        PageInfo<Knowledge> pageInfo = new PageInfo<>(knowledgeList);
        return pageInfo;
    }

    @Override
    public Knowledge selectById(Integer id) {
        Knowledge knowledge = knowledgeDao.selectByPrimaryKey(id);
        return knowledge;
    }

    @Override
    public PageInfo<Knowledge> findPageByKeys(String keys, Integer pageNum) {
        PageHelper.startPage(pageNum, pageSize);
        List<Knowledge> knowledges = knowledgeDao.selectAllByKeys(keys);
        PageInfo<Knowledge> knowledgePageInfo = new PageInfo<>(knowledges);
        return knowledgePageInfo;
    }

    @Override
    public List<Knowledge> selectByUsername(String name) {

        Knowledge knowledge = new Knowledge();
        knowledge.setOwnName(name);
        List<Knowledge> knowledgeList=knowledgeDao.selectByExample(knowledge);
        return knowledgeList;
    }

    @Override
    public void add(Knowledge knowledge) {
        UserDetails principal = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        String name = principal.getUsername();
        knowledge.setOwnName(name);
        knowledge.setCreateTime(new Date());
        knowledge.setUpdateTime(new Date());

        knowledgeDao.insertSelective(knowledge);
    }

    @Override
    public void update(Knowledge knowledge, Integer id) {
        knowledge.setKnowledgeId(id);
        knowledgeDao.updateByPrimaryKeySelective(knowledge);
    }

    @Override
    public void delete(Integer id) {
       knowledgeDao.deleteByPrimaryKey(id);
    }
}
